package com.gitee.feizns.explore.data_structure.array_and_string.rotate;

/**
 * @author feizns
 * @since 2019/10/25
 */
public class Rotate {

    static int[][] Arr = {
        {1,   2,  3,  4},
        {5,   6,  7,  8},
        {9,  10, 11, 12},
        {13, 14, 15, 16}
    };

    public static void main(String[] args) {
        print();

        rotate(Arr);

        System.out.println();
        System.out.println();

        print();
    }

    public static void rotate(int[][] matrix) {
        //
        rightDiagonalLineInHalf(matrix, matrix.length);

        //
        upAndDownExchange(matrix);
    }

    private static void rightDiagonalLineInHalf(int[][] matrix, int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ( isRightSlash(i, j, n) )
                    break;
                else {
                    int[] point = getRightPoint(i, j, n);
                    swap(matrix, i, j, point[0], point[1]);
                }
            }
        }
    }

    private static boolean isRightSlash(int r, int c, int n) {
        return r + c == n - 1;
    }

    public static int[] getRightPoint(int r, int c, int n) {
        return new int[]{ n - 1 - c, n - 1 - r };
    }

    private static void upAndDownExchange(int[][] matrix) {
        for (int i = 0; i < matrix[0].length; i++)
            colUpAndDownExchange(matrix, i);
    }

    private static void colUpAndDownExchange(int[][] matrix, int col) {
        int n = matrix.length;
        for (int i = 0; i < n / 2; i++) {
            swap(matrix, i,col, n - 1 - i, col);
        }
    }

    private static void swap(int[][] matrix, int x, int y, int x1, int y1) {
        int tmp = matrix[x][y];
        matrix[x][y] = matrix[x1][y1];
        matrix[x1][y1] = tmp;
    }

    private static void print() {
        for (int i = 0; i < Arr.length; i++) {
            for (int j = 0; j < Arr.length; j++) {
                System.out.print(Arr[i][j] + "\t");
            }
            System.out.println();
        }
    }

}
